package com.kaixinff.kaixin001.xw;

import java.util.LinkedList;
import java.util.List;

import com.kaixinff.name.User;


public class MainThread extends Thread{
	private static final int THREAD_NUM = 9;
	private int num;
	private List<UserWrap> users;
	private boolean[] flags;
	private boolean stoped = false;
	
	public MainThread(List<User> users, boolean[] flags) {
		this.users = new LinkedList<UserWrap>();
		for (User user: users) {
			this.users.add(new UserWrap(user));
		}
		this.flags = flags;
	}
	
	public synchronized void run() {
		for (int i = 0; i < THREAD_NUM; i++ ) {
			Thread t = new Thread(new Task(this, i, flags)); 
			t.start();
		}
		num = THREAD_NUM;
		while (num > 0) {
			try {
				wait();
				System.out.printf("There are %1$s active thread.", num);
				System.out.println();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("Main thread end!");
	}
	
	public synchronized void decNum() {
		num --;
	}
	
	public synchronized void setUser(UserWrap user) {
		for (int i = 0, n = users.size(); i < n; i++) {
			UserWrap u = users.get(i);
			if (user.getTime() < u.getTime()) {
				users.add(i, user);
				return;
			}
		}
		users.add(user);
	}
	
	public synchronized UserWrap getUser() {
		UserWrap user = null;
		if (users.size() > 0) {
			UserWrap u = users.get(0);
			if (System.currentTimeMillis() > u.getTime()) {
				user = users.remove(0);
			} else {
				user = new UserWrap(null);
				user.setTime(u.getTime());
			}
		}
		return user;
	}
}
